import {Button, ButtonProps, notification} from "antd";
import React from "react";
import {hasEmpower} from "@/config/route/route-func";
import {Empower} from "@/components/ant-ext/empower";
import HConfirm, {HConfirmProps} from "@/components/ant-ext/HConfirm";
import Constant from "@/config/constant";


export type HButtonProps = Empower & ButtonProps &
    {
        confirm?: { title: HConfirmProps["title"], ok?: () => void, cancel?: () => void } | string
    }

export default class HButton extends React.Component<HButtonProps, any> {

    state: { factory: () => React.ReactNode }

    constructor(props: HButtonProps) {
        super(props);
        this.rendNoBtn = this.rendNoBtn.bind(this)
        this.rendBtn = this.rendBtn.bind(this)
        if (hasEmpower(props.empower)) {
            this.state = {factory: this.rendBtn}
        } else {
            this.state = {factory: this.rendNoBtn}
        }
    }

    rendNoBtn() {
        const {empower, invalid, ...other} = this.props
        if (Constant.EmpowerVisible) {
            return <Button  {...other} onClick={() => {
                notification.error({message: "权限不足"})
                return false;
            }}/>
        } else if (invalid) {
            return other.children
        } else {
            return <></>
        }

    }

    rendBtn() {
        const {empower, invalid, ...other} = this.props
        return <Button {...other} />

    }


    render() {
        const {confirm, onClick} = this.props
        if (confirm) {
            let ok: HConfirmProps["ok"];
            let cancel: HConfirmProps["cancel"];
            let title: HConfirmProps["title"];
            if (typeof confirm === "string") {
                title = confirm
                ok = () => {
                    // @ts-ignore
                    onClick?.()
                }
                cancel = () => {
                }
            } else {
                ok = confirm.ok
                cancel = confirm.cancel
                title = confirm.title
            }
            return <HConfirm ok={ok} title={title} cancel={cancel}> {this.state.factory()}</HConfirm>;
        } else {
            return this.state.factory()
        }
    }
}

